package chen.jia.xin.finalproject.MainView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import chen.jia.xin.finalproject.BaseActivity;
import chen.jia.xin.finalproject.R;

public class ChatActivity extends BaseActivity implements View.OnClickListener {

    //聊天好友对象名
    private TextView friendTo;
    private List<Msg> msgList = new ArrayList<>();
    private Uri imageUri;
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;
    private Button take_photo;

    //点击事件处理
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send:
                String contentString = inputText.getText().toString();
                SpannableString content = new SpannableString(contentString);
                if(!"".equals(content)){
                    Msg msg = new Msg(content,Msg.TYPE_SEND);
                    msgList.add(msg);
                    //刷新显示
                    adapter.notifyItemInserted(msgList.size());
                    //使RecyclerView滑到指定的位置
                    msgRecyclerView.scrollToPosition(msgList.size()-1);
                    inputText.setText("");
                }
                break;
            case R.id.take_photo:
                //创建File对象，用于存储拍照后的图片
                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                try {
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //Android7以后，直接使用本地真实路径的Uri是不安全的，
                //而FileProvider是一种特殊的内容提供器
                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(ChatActivity.this, "fileProvider", outputImage);
                }else{
                    imageUri = Uri.fromFile(outputImage);
                }
                //启动相机程序
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                //把imageUri参数代入
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent,1);
        }
    }

    //startActivityForResult的返回结果，处理拍照结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    try {
                        //将拍摄的照片显示出来
                        //Bitmap图片对象
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        //将Bitmap对象转化为Drawable对象并定位
                        Drawable drawable = new BitmapDrawable(bitmap);
                        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        //图片对象（与输入框消息结合）
                        String source = " ";
                        if (!inputText.getText().toString().equals("")) {
                            source = inputText.getText().toString();
                        }
                        SpannableString spannable = new SpannableString(source);
                        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                        //setSpan方法把图片加入到SpannableString对象上
                        spannable.setSpan(span, source.length()-1, source.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        Msg msg = new Msg(spannable,Msg.TYPE_SEND);
                        msgList.add(msg);
                        //刷新显示
                        adapter.notifyItemInserted(msgList.size());
                        //使RecyclerView滑到指定的位置
                        msgRecyclerView.scrollToPosition(msgList.size()-1);
                        inputText.setText("");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_layout);
        //初始化消息
        initMsg();
        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        send.setOnClickListener(this);
        take_photo = findViewById(R.id.take_photo);
        take_photo.setOnClickListener(this);
        msgRecyclerView = findViewById(R.id.FyyRecycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);

        //显示好友名称
        friendTo = findViewById(R.id.chat_friend_name);
        Intent intent = getIntent();
        friendTo.setText(intent.getStringExtra("friendName"));
    }
    private void initMsg(){
        Msg msg1 = new Msg(new SpannableString("hello girl!"),Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg(new SpannableString("hello,how are you?"),Msg.TYPE_SEND);
        msgList.add(msg2);
        Msg msg3 = new Msg(new SpannableString("I'm fine!"),Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}
